﻿using AuthCenter.Api.Read.Application.Command.Apply;
using AuthCenter.Api.Read.Application.Output;
using AuthCenter.Application;
using AuthCenter.Domain;
using AuthCenter.ErrorCode;
using MD5Hash;
using MediatR;

namespace AuthCenter.Api.Read.Application.Hander.Apply
{
    public class GetReportShowHander:IRequestHandler<GetReportShowCommand, ApiResult<ReportOutput>>
    {
        private readonly IBaseRepository<ApplyModel> _applyRepository;
        public GetReportShowHander(IBaseRepository<ApplyModel> applyRepository)
        {
            _applyRepository = applyRepository;
        }
        /// <summary>
        /// 获取报表数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<ReportOutput>> Handle(GetReportShowCommand request, CancellationToken cancellationToken)
        {
            //实例化
            ApiResult<ReportOutput> res = new ApiResult<ReportOutput>();
          
            //根据全表查，查出申请人、请假时间、总工时
            var query = _applyRepository.GetAll().Where(x => !x.IsDeleted).Select(x => new
            {
                x.UserName,
                x.StartTime,
                x.EndTime,
                x.Hour,
            }).ToList();
            //int[]用于存储该员工 12个月 的请假天数
            var result = new Dictionary<string, int[]>();
            foreach (var item in query)//遍历每一条请假记录
            {
                //检查字典中是否已存在该员工
                if (!result.ContainsKey(item.UserName)) 
                {
                    //如果不存在，为该员工创建一个长度为12的数组，对应着12个月
                    result[item.UserName] = new int[12];
                }
                //获取当前记录的请假开始时间和结束时间
                var currentDate = item.StartTime;
                var endData = item.EndTime;
                //逐天处理请假时间段
                while (currentDate <= endData) 
                {
                    //计算当前日期所在的月份索引(0-11)
                    var monthIndex = currentDate.Month - 1;
                    //计算当天请假的小时数
                    var dailyHours = currentDate.Date == endData.Date//如果是请假的最后一天
                          ? (int)(endData - currentDate).TotalHours//计算实际小时数
            : currentDate.Date == item.StartTime.Date//如果是请假的第一天
                ? (int)(currentDate.Date.AddDays(1) - currentDate).TotalHours//计算第一天的小时数
                : 8;//整天按8小时计算
                    //累加到对应用户的对应月份
                    result[item.UserName][monthIndex] += dailyHours;
                    //获取下一天
                    currentDate=currentDate.AddDays(1);
                    currentDate=new DateTime(currentDate.Year,currentDate.Month,currentDate.Day,0,0,0);
                }
            }
            var dto=new ReportOutput
            {
                LeaveApplicationList = result
            };
            if (!string.IsNullOrEmpty(request.UserName)) 
            {
                dto.LeaveApplicationList=dto.LeaveApplicationList.Where(x=>x.Key.Contains(request.UserName)).ToDictionary(x=>x.Key,x=>x.Value);
            }
            res.Code=ApiEnums.OK;
            res.Message="查询成功";
            res.Data=dto;
            return Task.FromResult(res);
        }
    }
}
